package com.monkeyboy.tool.gen.service;

import com.monkeyboy.common.Constants;
import com.monkeyboy.common.utils.StringUtils;
import com.monkeyboy.dao.BaseDao;
import com.monkeyboy.model.GenTable;
import com.monkeyboy.model.GenTableColumn;
import com.monkeyboy.tool.gen.util.VelocityInitializer;
import com.monkeyboy.tool.gen.util.VelocityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @Author Gavin
 * @date 2020.07.10 12:30
 */
@Slf4j
@Service
public class GenService {
    @Autowired
    private BaseDao bd;

    public byte[] generatorCode(String tableName) throws Exception {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        generatorCode(tableName, zip);
        IOUtils.closeQuietly(zip);
        return outputStream.toByteArray();
    }

    /*
    生成代码的核心逻辑
     */
    private void generatorCode(String tableName, ZipOutputStream zip) throws Exception {
        //查询表的信息
        GenTable table = (GenTable) bd.findForObject("GenCodeMapper.selectGenTableByName" , tableName);
        //获取列的信息
        List<GenTableColumn> columns = table.getColumns();
        setPkColumn(table, columns);//设置主键信息
        VelocityInitializer.initVelocity();
        VelocityContext context = VelocityUtils.prepareContext(table);

        // 获取模板列表
        List<String> templates = VelocityUtils.getTemplateList(table.getTplCategory());
        for (String template : templates) {
            // 渲染模板
            StringWriter sw = new StringWriter();
            Template tpl = Velocity.getTemplate(template, Constants.UTF8);
            tpl.merge(context, sw);
            try {
                // 添加到zip
                zip.putNextEntry(new ZipEntry(VelocityUtils.getFileName(template, table)));
                IOUtils.write(sw.toString(), zip, Constants.UTF8);
                IOUtils.closeQuietly(sw);
                zip.flush();
                zip.closeEntry();
            } catch (IOException e) {
                log.error("渲染模板失败，表名：" + table.getTableName(), e);
            }
        }
    }

    //设置主键信息
    private void setPkColumn(GenTable table, List<GenTableColumn> columns) throws Exception {
        for (GenTableColumn column : columns) {
            if (column.isPk()) {
                table.setPkColumn(column);
                break;
            }
        }
        if (StringUtils.isNull(table.getPkColumn())) {
            table.setPkColumn(columns.get(0));
        }
    }
}
